/* Copyright 2010 John L. Reilly

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */

package com.riq;

import java.io.IOException;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.riq.entity.Department;
import com.riq.entity.Icon;
import com.riq.entity.Marker;

public class AdminMarkerServlet extends HttpServlet {
  private static final long serialVersionUID = 1L;
  private static final Logger log = Logger.getLogger(AdminMarkerServlet.class.getName());
  
  private List<Long> deptsIncluded = new ArrayList<Long>();
  private Long deptId = Long.valueOf("9999999");
  private String memberId;
  private String mutualAid;
  
  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response)
  throws ServletException, IOException {
    doGet(request, response);
  }
  
  @Override
  public void doGet(HttpServletRequest request, HttpServletResponse response)
  throws ServletException, IOException { 
    
  // ---------------------------------------------------------------------------------------------
  //  HEADER: MARKER
  // ---------------------------------------------------------------------------------------------

  Cookie[] cookie = request.getCookies();
  deptId = Long.valueOf(ServletUtilities.getCookieValue(cookie, "cvDeptId", "99999"));  
  memberId = String.valueOf(ServletUtilities.getCookieValue(cookie, "cvMemberId", "99999"));
//  mutualAid = String.valueOf(ServletUtilities.getCookieValue(cookie, "cvMutualAid", "99999"));
  
  if (deptId == null) {
      response.sendRedirect("noSuchObject?errorMessage=NoPermission");
  }
  
  String action = request.getParameter("action"); 
  String intent = request.getParameter("intent");   

  // ---------------------------------------------------------------------------------------------
  //  METHOD DIRECTORY: MARKER
  // ---------------------------------------------------------------------------------------------
    
  if ("prepCreate".equalsIgnoreCase(action)) { 
    prepCreate(response, request, intent); 
  } else if ("create".equalsIgnoreCase(action)) { 
    create(response, request); 
  } else if ("delete".equalsIgnoreCase(action)) { 
    delete(response, request); 
  } else if ("kml".equalsIgnoreCase(action)) { 
    kml(response, request); }
  }

  // ---------------------------------------------------------------------------------------------
  //  METHODS: MARKER
  // ---------------------------------------------------------------------------------------------
  
  
  private void prepCreate(HttpServletResponse response, ServletRequest request, 
       String intent) {

    PersistenceManager pm = PMF.get().getPersistenceManager();
    request.setAttribute("deptId", deptId.toString());
    request.setAttribute("memberId", memberId);
    
    //TODO: possibly show Mutual Aid markers to avoid duplication

//  // add primary department to list of markers to retrieve
//  log.info("deptId inside markerservlet: " + deptId.toString());
//  deptsIncluded.add(Long.valueOf(deptId));
//  
//  // add mutual aid departments to show their markers to primary dept
//  String[] maDepts = mutualAid.split(", ", -1);
//  for (int j=0; j< maDepts.length; j++) {
//    Long maDeptId = Long.valueOf(maDepts[j]);
//    deptsIncluded.add(maDeptId);
//    log.info("deptId inside markerservlet pass: " + j + "|" + maDeptId.toString());
//  }
    
    Query queryI = pm.newQuery(Icon.class, " deptId == " + deptId );
    queryI.setOrdering("shortName asc");
    List<Icon> icons = (List<Icon>) pm.newQuery(queryI).execute();
    request.setAttribute("icons", icons);
    
    Query queryM = pm.newQuery(Marker.class, " deptId == " + deptId );
    queryM.setOrdering("pubDate desc");
    List<Marker> markers = (List<Marker>) pm.newQuery(queryM).execute();
    
    String timeStamp = String.valueOf(System.currentTimeMillis());
    String deptIdString = String.valueOf(deptId);
    response.setContentType("text/xml");
    String finalURL = "http://responderiq05.appspot.com/marker?action=kml&deptId=" + 
    deptIdString + "&time=" + timeStamp;
    System.out.println ("FinalURL: " + finalURL);
    request.setAttribute("urlRoot", finalURL);
    request.setAttribute("deptId", deptIdString);

    String startLat = "";
    String startLng = "";
   
    if (!markers.isEmpty()) {
      startLat = markers.get(0).getlatitude();
      startLng = markers.get(0).getlongitude();
    } else {
      startLat = "40.242";
      startLng = "-74.34";
    }

    request.setAttribute("startLat", startLat);
    request.setAttribute("startLng", startLng);

    if ("command".equalsIgnoreCase(intent)) {
      RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/markerCommand.jsp");
      try
      {
        dispatcher.forward(request, response);
      } catch (ServletException e)
      {
        // TODO Auto-generated catch block
        e.printStackTrace();
      } catch (IOException e)
      {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    } else {
      RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/markerCreate.jsp");
      try
      {
        dispatcher.forward(request, response);
      } catch (ServletException e)
      {
        // TODO Auto-generated catch block
        e.printStackTrace();
      } catch (IOException e)
      {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
  }
  
  
  private void create(HttpServletResponse response, ServletRequest request) {

    log.info("Inside AdminMarkerServlet:Create");

    Marker mk = new Marker (
            Long.valueOf(request.getParameter("memberId")),
            Long.valueOf(request.getParameter("deptId")),
            request.getParameter("markerLat"),
            request.getParameter("markerLng"),
            request.getParameter("type"),
            request.getParameter("title"),
            request.getParameter("descr"),
            System.currentTimeMillis()
    );
    
//    log.info("markerLat: " + mk.getlatitude());
//    log.info("markerLng: " + mk.getlongitude());
//    log.info("markertype: " + mk.gettype());
//    log.info("markerTitle: " + mk.gettitle());
//    log.info("markerDescription: " + mk.getdescription());

    PersistenceManager pm = PMF.get().getPersistenceManager();
    pm.makePersistent(mk);
    pm.close();

      try
      {
        response.sendRedirect("marker?action=prepCreate&deptId=" + request.getParameter("deptId"));
      } catch (IOException e)
      {
        // TODO Auto-generated catch block
        e.printStackTrace();
      } 
  }

  
  private void delete(HttpServletResponse response, ServletRequest request) {
    
    PersistenceManager pm = PMF.get().getPersistenceManager();
    Long markerId = Long.valueOf(request.getParameter("markerId"));
    Marker mk = pm.getObjectById(Marker.class, markerId);
    pm.deletePersistent(mk);
    pm.close();
    
    try
    {
      response.sendRedirect("marker?action=prepCreate");
    } catch (IOException e)
    {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
  

  
  private void kml(HttpServletResponse response, ServletRequest request) 
      throws IOException {
    
    PersistenceManager pm = PMF.get().getPersistenceManager();
    Long deptId = Long.valueOf(request.getParameter("deptId"));
    Department d = (Department) pm.getObjectById(Department.class, deptId);

    // add primary department to list of markers to retrieve
    deptsIncluded.add(Long.valueOf(deptId));

    // add mutual aid departments to show their markers to primary dept
    String[] maDepts = d.getmutualAid().split(", ", -1);
    for (int j=0; j< maDepts.length; j++) {
      Long maDeptId = Long.valueOf(maDepts[j]);
      deptsIncluded.add(maDeptId);
    }

    Query qM = pm.newQuery(Marker.class, " :p.contains(deptId)");
    qM.setOrdering("type asc");
    List<Marker> markers = (List<Marker>) pm.newQuery(qM).execute(deptsIncluded); 

    Query qI = pm.newQuery(Icon.class, " :p.contains(deptId)");
    qI.setOrdering("shortName asc");
    List<Icon> icons = (List<Icon>) pm.newQuery(qI).execute(deptsIncluded); 
    
    PrintStream out;
    
    response.setContentType("application/vnd.google-earth.kml+xml");
    out = new PrintStream(response.getOutputStream());

    out.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
    out.println("<kml xmlns=\"http://www.opengis.net/kml/2.2\">");
    out.println("<Document>");
    
    for (Icon i : icons) {
        out.println("<Style id=\"" + i.getshortName() + "\">" + 
                "<IconStyle>" + 
                "<Icon>" +
                "<scale>1</scale>" +
                "<href>" +
                "http://chart.apis.google.com/chart?cht=d&amp;chl=" + 
                i.getshortName() +
                "'h\\" +
                i.getpadL() + "'-" +
                i.getpadB() + "'" +
                i.getpadT() + "'-" +
                i.getpadR() + "'dim'\\box1'b\\" +
                i.getbcolor() + "'fC\\" +
                i.getfcolor() + "'tC" +
                "</href></Icon>" +
                "</IconStyle>" +
                "</Style>");
    }
    
    // chartmaker template for icon
    // http://chart.apis.google.com/chart?cht=d&chl=E304'h\4'-3'3'-5'dim'\box1'b\0080ff'fC
    // chart.apis.google.com/chart?cht=d&chl=E304'h\4'-3'3'-5'dim'\box1'b\0080ff'fC\\ffffff'tC
    
    for (Marker mk : markers) {
   
      out.println(
              
      "<Placemark>" + 
      "<name>" + mk.gettitle() + "</name>" + 
      
      "<![CDATA[<a href=\"marker?action=delete&markerId=" 
      + mk.getid() + 
      "\">Delete?</a>]]>" +
     
      "<styleUrl>#" 
      + mk.gettype() + 
      "</styleUrl>" +
      
      "<description>" +
      "<![CDATA[" + mk.getdescription() + "<br>" +
      "<a href=\"marker?action=delete&markerId=" +
      + mk.getid() + 
      "\">Delete?</a>" +
      "]]>" +
      "</description>" +
      
      "<Point>" +
      "<coordinates>" 
      + mk.getlongitude() + "," + mk.getlatitude() + 
      "</coordinates>" + 
      "</Point>" +
      
      "</Placemark>"
      );
    }
  
    out.println("</Document></kml>");
    out.flush();
    out.close();
    
  }
}

